package converters;

import dtos.LeaveTypeDTO;
import user.ScheduleBean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import java.util.List;

@ManagedBean(name = "leaveTypeConverter")
@SessionScoped
public class LeaveTypeConverter implements Converter {

    @ManagedProperty(value = "#{scheduleBean}")
    private ScheduleBean scheduleBean;

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        try {
            int leaveTypeId = Integer.parseInt(s);
            List<LeaveTypeDTO> leaveTypes = scheduleBean.getLeaveTypes();
            for (LeaveTypeDTO lt : leaveTypes) {
                if (lt.getId() == leaveTypeId) {
                    return lt;
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        if (o == null || o.equals("")) {
            return "";
        } else {
            return String.valueOf(((LeaveTypeDTO) o).getId());
        }
    }

    public ScheduleBean getScheduleBean() {
        return scheduleBean;
    }

    public void setScheduleBean(ScheduleBean scheduleBean) {
        this.scheduleBean = scheduleBean;
    }
}
